<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <img src="@/assets/images/avatar.gif" alt="avatar" />
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="openChangePasswordDialog()">
          <SvgIcon name="Edit"></SvgIcon>
          {{ _transitionLanguages('header', 'changePassword') }}
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <SvgIcon name="SwitchButton"></SvgIcon>
          {{ _transitionLanguages('header', 'logout') }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>

  <DialogForm
    :width="changePwdForm.width"
    :form-cols="changePwdForm.formCols"
    :options="changePwdForm.options"
    :title="changePwdForm.title"
    :form-attrs="changePwdForm.formAttrs"
    v-model:visible="changePwdForm.visible"
    @get-model="(form: User.ReqChangePassword) => (changePwdForm.form = form)"
    @submit-form="savePwdForm"
  ></DialogForm>
</template>

<script setup lang="ts">
import { LOGIN_URL } from '@/config';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';

import { changePwdForm, savePwdForm } from '../mixins/passwordForm';

import { User } from '@/api/interface';

const router = useRouter();
const userStore = useUserStore();

// 语言转换
const _transitionLanguages = (v: string, l: string): string => {
  return transitionLanguages(v, l);
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm(_transitionLanguages('title', 'outLogin'), _transitionLanguages('basic', 'gentleReminder'), {
    confirmButtonText: _transitionLanguages('button', 'confirm'),
    cancelButtonText: _transitionLanguages('button', 'cancel'),
    type: 'warning'
  }).then(async () => {
    // 1.执行退出登录接口
    await logoutApi();

    // 2.清除 Token
    userStore.setToken('');

    // 3.重定向到登陆页
    router.replace(LOGIN_URL);
    ElMessage.success(_transitionLanguages('basic', 'logOutSuccessfully'));
  });
};

// 打开修改密码弹框
const openChangePasswordDialog = () => {
  formOpen<User.ReqChangePassword>(changePwdForm, 'changePassword');
};
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
